<template>
  <div class="head-form-box">
    <el-form
      :inline="true"
      :model="listQuery"
      label-width="80px"
      label-position="left"
      class="header-form"
      size="small"
      @keyup.enter.native="handleReset"
    >
      <el-form-item v-for="item in searchColumn" :key="item.key" :label="`${item.label}:`">
        <el-select
          v-if="item.type === 'select'"
          v-model="listQuery[item.key]"
          :placeholder="item.pla || `请选择${item.label}`"
        >
          <el-option
            v-for="oItem in item.options"
            :key="oItem.value"
            :label="oItem.label"
            :value="oItem.value"
          />
        </el-select>
        <el-input
          v-else
          v-model="listQuery[item.key]"
          :placeholder="item.pla || `请输入${item.label}`"
          clearable
        />
      </el-form-item>
    </el-form>
    <div class="header-but">
      <div class="left-but">
        <slot name="left" />
      </div>
      <div class="right-but">
        <el-button type="primary" size="small" @click="handleSearch">搜索</el-button>
        <el-button type="primary" plain size="small" @click="handleReset">重置</el-button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'HeaderForm',
  props: {
    searchColumn: {
      type: Array,
      default() {
        return []
      }
    },
    value: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      listQuery: {}
    }
  },
  watch: {
    searchColumn: {
      handler() {
        const tempListQ = this.searchColumn.reduce((pre, cur) => {
          pre[cur.key] = ''
          return pre
        }, {})
        this.listQuery = Object.assign(this.listQuery, tempListQ)
      }
    },
    listQuery: {
      handler(val) {
        this.$emit('input', val)
      }
    }
  },
  created() {
    this.listQuery = this.value
  },
  methods: {
    handleReset() {
      const tempListQ = this.searchColumn.reduce((pre, cur) => {
        pre[cur.key] = ''
        return pre
      }, {})
      this.listQuery = Object.assign(this.listQuery, tempListQ)
      this.$emit('reset', this.listQuery)
    },
    handleSearch() {
      this.$emit('search', this.listQuery)
    }
  }
}
</script>

<style scoped lang="scss">
.head-form-box {
  width: 100%;
  &::v-deep .el-form {
    margin-right: -10px;
    .el-form-item {
      width: calc(100% / 4 - 10px);
      min-width: 172px;
      .el-form-item__content {
        width: calc(100% - 80px);
      }
    }
  }
}
.header-but {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
</style>
